package com.bigdata;


public class ThreadSafeDemo2 implements Runnable {

    private Object lock;
    private int num = 0;

    public ThreadSafeDemo2() {
    }

    public ThreadSafeDemo2(Object lock) {
        this.lock = lock;
    }

    //    private AtomicInteger num = new AtomicInteger(0);

    // ArrayList, 是线程不安全的

    public void incrNum() {
        System.out.println("this:" + this);
        // 一个对象可以作为一把锁，
        synchronized (lock) {
//        synchronized (new Object()) {
            for (int i = 0; i < 5000; i++) {
                num++;
//            num.incrementAndGet();
            }
        }

    }

    @Override
    public void run() {
        incrNum();
    }

    public static void main(String[] args) throws InterruptedException {

        // 锁对象
        Object lock = new Object();

        // ThreadSafeDemo2 里面定义了run逻辑，
        // 并且num变量也是ThreadSafeDemo2类的对象里面的属性
        ThreadSafeDemo2 safeDemo2 = new ThreadSafeDemo2(lock);

        System.out.println("safeDemo2:" + safeDemo2);

        Thread t1 = new Thread(safeDemo2);
        Thread t2 = new Thread(safeDemo2);

        // t1和t22个线程，同时执行，对同一个对象中的num值自增500次
        t1.start();
        t2.start();

        Thread.sleep(500);

        System.out.println(safeDemo2.num);

    }


}
